package com.cyz.common.utils;

import com.cyz.common.enums.MyEnums;
import com.cyz.common.exception.MyException;
import com.cyz.common.security.MyUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

public class SecurityUtils
{

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前是否登录
     * @return
     */
    public static boolean IsLogin(){
        return !String.valueOf(getAuthentication().getPrincipal()).equals("anonymousUser");
    }

    /**
     * 获取用户
     **/
    public static MyUserDetails getLoginUser()
    {
        if(IsLogin()){
            return (MyUserDetails) getAuthentication().getPrincipal();
        }
        throw new MyException(MyEnums.LOGIN_FAIL);
    }


    /**
     * 验证用户是否是超级管理员
     * @return
     */
    public static boolean IsAdmin(){
        return Objects.equals(getUserId(), MyEnums.ADMIN_ID);
    }

    /**
     * 获取当前用户的id
     * @return
     */
    public static Integer getUserId() {
        return getLoginUser().getUser().getId();
    }
}